-- UITreeHouseSubmit
-- Created by cheny3 Feb/23/2016
-- 树屋提交

require "game/ui/form/equips/UIEquipTooltip"
require "game/ui/form/equips/UIEquips"

-- UITreeHouseSubmit 继承自Layer
UITreeHouseSubmit = class("UITreeHouseSubmit", function()
    return cc.Layer:create();
end);

function UITreeHouseSubmit.create(classId, pos)
    return UITreeHouseSubmit.new(classId, pos);
end

-- 内部函数声明
local resize;
local SUBMIT_NUMS = 4;

-- 构造函数
function UITreeHouseSubmit:ctor(classId, pos)
    self:setName("UITreeHouseSubmit");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/dungeon/BuildingView6.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.classId = classId;
    self.pos = pos;

    -- 提交信息
    self.submited = {};

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 自适应
    self:alignAdaptLayout();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UITreeHouseSubmit:registerEventCallback()
    -- 关注工坊放入装备的事件
    EventMgr.register("UITreeHouseSubmit", event.BLACKSMITH_INPUT_EQUIP, function(args)
        self:whenInputEquip(args);
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UITreeHouseSubmit 界面析构清理");
            EventMgr.removeAll("UITreeHouseSubmit");
        elseif eventType == "enter" then
            -- TODO
        end
    end);
end

-- 注册点击事件
function UITreeHouseSubmit:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            -- 先把选择框中脱下来的装备穿上去
            self.submited = self.submited or {};
            for _, info in pairs(self.submited) do
                local classId = info.class_id;
                local isUnequiped = info.isUnequiped;
                if type(classId) == "number" and isUnequiped then
                    DungeonActionM.go("do_equip", 0, classId);
                end
            end

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UITreeHouseSubmit");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 注册确定按钮点击事件
    local btnOk = findChildByName(node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_confirm");
            if #table.values(self.submited) < SUBMIT_NUMS then
                return;
            end

            for _, info in pairs(self.submited) do
                -- 提交道具
                DungeonActionM.go("tree_house_submit", self.pos, info["class_id"]);
            end
            -- 关闭界面
            UIMgr.getCurrentScene():removeFormByName("UITreeHouseSubmit");
        end
    end
    btnOk:addTouchEventListener(onOkClick);

    -- 注册装备点击格点击事件
    self.itemGrids = self.itemGrids or {};
    for i = 1, 4 do
        local itemGrid = findChildByName(self.node, "CT/skill_panel/item" .. i);
        itemGrid.index = i;
        self.itemGrids[i] = itemGrid;
        -- 注册点击
        self:registerItemClick(itemGrid);
    end
end

-- 注册装备格点击事件
function UITreeHouseSubmit:registerItemClick(node)
    local frame = findChildByName(node, "frame");
    local function onEquipClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 取出所有提交的装备的class_id
            local submitList = {};
            for _, info in pairs(self.submited or {}) do
                if type(info.class_id) == "number" then
                    table.insert(submitList, info.class_id);
                end
            end

            -- 打开装备选择界面
            -- 传入参数：通过树屋方式打开
            local uiEquip = UIEquips.create(EQUIP_OPEN_TYPE_TREE_HOUSE, {["index"] = node.index,
                ["treeId"] = self.classId, ["submited"] = submitList,});
            UIMgr.getCurrentScene():addForm(uiEquip);
        end
    end
    frame:addTouchEventListener(onEquipClick);
end

-- 自适应位置
function UITreeHouseSubmit:alignAdaptLayout()
    local bg = findChildByName(self.node, "CT/bg1");
    local desc = findChildByName(self.node, "CT/desc");
    local icon = findChildByName(self.node, "CT/icon");
    local skillPanel = findChildByName(self.node, "CT/skill_panel");
    local detail = findChildByName(self.node, "CT/detail");
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local titleNode = findChildByName(self.node, "CT/title_node");

    local nodeArr = {desc, icon, skillPanel, detail, btnOk};
    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL, nodeArr, {10, 10, nil}, 100);

    -- 计算标题新位置
    local bgScale = bg:getScaleY();
    local newPosY = titleNode:getPositionY() * bgScale;
    titleNode:setPositionY(newPosY);
end

-- 重绘
function UITreeHouseSubmit:redraw()
    local CT = findChildByName(self.node, "CT");
    local BT = findChildByName(self.node, "BT");

    -- 显示标题
    local title = TreeHouseM.query(self.classId, "name");
    local titleLabel = findChildByName(CT, "title_node/title");
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_CYAN, true);
    titleLabel:setString(title);
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 显示功能描述
    local desc = TreeHouseM.query(self.classId, "no_active_desc");
    local descLabel = findChildByName(CT, "desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(descLabel, desc);

    -- 详细描述
    local detail = TreeHouseM.query(self.classId, "submit_tip");
    local detailLabel = findChildByName(CT, "detail");
    TextStyleM.setTextStyle(detailLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(detailLabel, detail);

    -- 显示建筑图标
    local mainIcon = findChildByName(CT, "icon");
    local iconName = TreeHouseM.query(self.classId, "icon");
    local iconPath = getLevelItemIconPath(iconName);
    mainIcon:loadTexture(iconPath);

    local effectNode = mainIcon.monkeyNode;
    if not mainIcon.monkeyNode then
        -- 没有节点创建一个
        effectNode = cc.Node:create();
        mainIcon:addChild(effectNode);
        mainIcon.monkeyNode = effectNode;
    end
    effectNode:removeAllChildren();

    local treeHouse = ME.user.tree_house;
    if not treeHouse or not treeHouse:isActive() then
        -- 未激活，待机状态
        playEffect(effectNode, 1325, 80, 100);
    end

    -- 提交框
    self.itemGrids = self.itemGrids or {};
    for i = 1, 4 do
        local itemGrid = findChildByName(CT, "skill_panel/item" .. i);
        itemGrid.index = i;
        self.itemGrids[i] = itemGrid;
    end
    self:redrawEquip();

    -- 显示确定按钮
    local btnOk = findChildByName(CT, "btn_ok");
    if #table.values(self.submited) >= SUBMIT_NUMS then
        -- 有足够装备
        btnOk:setBright(true);
        btnOk:setTouchEnabled(true);
    else
        btnOk:setBright(false);
        btnOk:setTouchEnabled(false);
    end
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(getLocStr("btn_text_submit"));

    -- 显示返回按钮
    local btnBack = findChildByName(BT, "btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 重绘装备格
function UITreeHouseSubmit:redrawEquip()
    -- 取出提交的装备的class_id
    self.submited = self.submited or {};
    self.itemGrids = self.itemGrids or {};

    for _, itemNode in pairs(self.itemGrids) do
        local info = self.submited[itemNode.index];
        local icon = findChildByName(itemNode, "icon");
        if info and info.class_id then
            icon:loadTexture(getItemIconPath(ItemM.query(info.class_id, "icon")));
            icon:setOpacity(255);
        else
            -- 没有除了默认物品（火把等）外时显示
            local showItemList = TreeHouseM.getDefaultList();
            if TreeHouseM.hasSpecialItem() then
                -- 组合图标
                icon:loadTexture(getLevelItemIconPath("tree_house_item"));
            else
                icon:loadTexture(getItemIconPath(ItemM.query(showItemList[itemNode.index], "icon")));
            end
            icon:setOpacity(100);
        end
    end
end

-- 工坊放入装备的回调
function UITreeHouseSubmit:whenInputEquip(args)
    local equipId = args.classId;
    local index = args.index;

    local isEquiped = args.isEquiped;
    if not equipId then
        return;
    end

    -- 记录装备id
    local submited = self.submited or {};
    submited[index] = {["class_id"] = equipId, ["isUnequiped"] = isEquiped };
    self.submited = submited;

    -- 重绘装备格
    self:redraw();
end
